import axios from "axios";
import { ElMessage } from "element-plus";
import qs from "qs";
import { useUserStore } from "../store/user";

const service = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

// 拦截请求
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      // 让每个请求携带token
      config.headers["Authorization"] = userStore.token;
    }

    // 只针对get方式进行序列化,序列化数组参数
    if (config.method === "get") {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 拦截响应
service.interceptors.response.use(
  (response) => {
    // code为非200是抛错
    const res = response.data;
    if (res.code !== 200) {
      ElMessage({
        message: res.message,
        type: "error",
        duration: 3 * 1000,
      });

      return Promise.reject("error");
    } else {
      return response.data;
    }
  },
  (error) => {
    ElMessage({
      message: error.message,
      type: "error",
      duration: 3 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
